<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="6">
        <el-card shadow="hover">
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <div>
              <div style="color: #909399; font-size: 14px; margin-bottom: 8px;">总权限数</div>
              <div style="font-size: 28px; font-weight: bold; color: #409EFF;">{{ stats.total }}</div>
            </div>
            <i class="el-icon-tickets" style="font-size: 48px; color: #409EFF; opacity: 0.3;"></i>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <div>
              <div style="color: #909399; font-size: 14px; margin-bottom: 8px;">有效权限</div>
              <div style="font-size: 28px; font-weight: bold; color: #67C23A;">{{ stats.active }}</div>
            </div>
            <i class="el-icon-circle-check" style="font-size: 48px; color: #67C23A; opacity: 0.3;"></i>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <div>
              <div style="color: #909399; font-size: 14px; margin-bottom: 8px;">即将过期</div>
              <div style="font-size: 28px; font-weight: bold; color: #E6A23C;">{{ stats.expiring }}</div>
            </div>
            <i class="el-icon-warning" style="font-size: 48px; color: #E6A23C; opacity: 0.3;"></i>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <div>
              <div style="color: #909399; font-size: 14px; margin-bottom: 8px;">已过期</div>
              <div style="font-size: 28px; font-weight: bold; color: #F56C6C;">{{ stats.expired }}</div>
            </div>
            <i class="el-icon-circle-close" style="font-size: 48px; color: #F56C6C; opacity: 0.3;"></i>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userOpenid">
        <el-input
          v-model="queryParams.userOpenid"
          placeholder="请输入OpenID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="视频标题" prop="videoTitle">
        <el-input
          v-model="queryParams.videoTitle"
          placeholder="请输入视频标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select v-model="queryParams.paymentMethod" placeholder="请选择支付方式" clearable>
          <el-option label="微信小程序" value="wechat" />
          <el-option label="H5微信支付" value="h5" />
          <el-option label="手动授予" value="manual" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="有效" value="active" />
          <el-option label="即将过期" value="expiring" />
          <el-option label="已过期" value="expired" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['video:permission:add']"
        >授予权限</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-time"
          size="mini"
          :disabled="multiple"
          @click="handleBatchExtend"
          v-hasPermi="['video:permission:edit']"
        >批量延期</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefreshStatus"
          v-hasPermi="['video:permission:edit']"
        >刷新状态</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['video:permission:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="permissionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户信息" align="left" min-width="150">
        <template slot-scope="scope">
          <div>
            <div style="font-weight: bold; margin-bottom: 5px;">{{ scope.row.userName || '未知用户' }}</div>
            <div style="font-size: 12px; color: #909399;">{{ scope.row.userOpenid }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="视频信息" align="left" min-width="150">
        <template slot-scope="scope">
          <div>
            <div style="font-weight: bold; margin-bottom: 5px;">{{ scope.row.videoTitle }}</div>
            <div style="font-size: 12px; color: #909399;">ID: {{ scope.row.videoId }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单信息" align="left" min-width="180">
        <template slot-scope="scope">
          <div>
            <div style="font-family: monospace; font-size: 12px; margin-bottom: 5px;">{{ scope.row.orderNo }}</div>
            <div>
              <el-tag v-if="scope.row.paymentMethod === 'wechat'" type="success" size="mini">微信小程序</el-tag>
              <el-tag v-else-if="scope.row.paymentMethod === 'h5'" type="primary" size="mini">H5微信</el-tag>
              <el-tag v-else type="info" size="mini">手动授予</el-tag>
              <span style="margin-left: 8px; color: #f56c6c; font-weight: bold;">¥{{ scope.row.price }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="购买时间" align="center" width="160">
        <template slot-scope="scope">
          <div style="font-size: 12px;">{{ parseTime(scope.row.purchaseTime, '{y}-{m}-{d} {h}:{i}') }}</div>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" width="160">
        <template slot-scope="scope">
          <div style="font-size: 12px;">{{ parseTime(scope.row.expireTime, '{y}-{m}-{d} {h}:{i}') }}</div>
        </template>
      </el-table-column>
      <el-table-column label="剩余时间" align="center" width="120">
        <template slot-scope="scope">
          <div :style="getRemainTimeStyle(scope.row)">{{ calcRemainTime(scope.row.expireTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 'active'" type="success">有效</el-tag>
          <el-tag v-else-if="scope.row.status === 'expiring'" type="warning">即将过期</el-tag>
          <el-tag v-else type="danger">已过期</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-time"
            @click="handleExtend(scope.row)"
            v-hasPermi="['video:permission:edit']"
          >延长</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['video:permission:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 授予权限对话框 -->
    <el-dialog title="授予播放权限" :visible.sync="open" width="600px" append-to-body>
      <el-alert
        title="手动授予的权限不会生成支付订单，仅用于赠送、补偿等场景"
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 20px;">
      </el-alert>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户OpenID" prop="userOpenid">
          <el-input v-model="form.userOpenid" placeholder="请输入用户openid，例如: oXXXX123456" />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名称（可选）" />
        </el-form-item>
        <el-form-item label="视频ID" prop="videoId">
          <el-input-number v-model="form.videoId" :min="1" controls-position="right" style="width: 100%;" />
          <div style="font-size: 12px; color: #909399; margin-top: 5px;">从视频管理中获取视频ID</div>
        </el-form-item>
        <el-form-item label="视频标题" prop="videoTitle">
          <el-input v-model="form.videoTitle" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="权限时长" prop="durationDays">
          <el-select v-model="form.durationDays" placeholder="请选择权限时长">
            <el-option label="1天" :value="1" />
            <el-option label="7天" :value="7" />
            <el-option label="30天" :value="30" />
            <el-option label="90天" :value="90" />
            <el-option label="永久(365天)" :value="365" />
          </el-select>
        </el-form-item>
        <el-form-item label="购买时间" prop="purchaseTime">
          <el-date-picker
            v-model="form.purchaseTime"
            type="datetime"
            placeholder="选择购买时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="例如：赠送活动、客服补偿等" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 延长权限对话框 -->
    <el-dialog title="延长权限" :visible.sync="extendOpen" width="400px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="当前到期">
          <div style="color: #606266;">{{ currentExpireTime }}</div>
        </el-form-item>
        <el-form-item label="延长天数">
          <el-input-number v-model="extendDays" :min="1" :max="365" controls-position="right" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="延长后到期">
          <div style="color: #67C23A; font-weight: bold;">{{ newExpireTime }}</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitExtend">确 定</el-button>
        <el-button @click="extendOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量延期对话框 -->
    <el-dialog title="批量延长权限" :visible.sync="batchExtendOpen" width="400px" append-to-body>
      <el-alert
        :title="`将为选中的 ${ids.length} 个权限延长有效期`"
        type="warning"
        :closable="false"
        show-icon
        style="margin-bottom: 20px;">
      </el-alert>
      <el-form label-width="100px">
        <el-form-item label="延长天数">
          <el-input-number v-model="batchExtendDays" :min="1" :max="365" controls-position="right" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchExtend">确 定</el-button>
        <el-button @click="batchExtendOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="权限详情" :visible.sync="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border v-if="currentPermission">
        <el-descriptions-item label="权限ID">{{ currentPermission.permissionId }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="currentPermission.status === 'active'" type="success">有效</el-tag>
          <el-tag v-else-if="currentPermission.status === 'expiring'" type="warning">即将过期</el-tag>
          <el-tag v-else type="danger">已过期</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="用户OpenID">{{ currentPermission.userOpenid }}</el-descriptions-item>
        <el-descriptions-item label="用户名称">{{ currentPermission.userName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="视频ID">{{ currentPermission.videoId }}</el-descriptions-item>
        <el-descriptions-item label="视频标题">{{ currentPermission.videoTitle }}</el-descriptions-item>
        <el-descriptions-item label="订单号" :span="2">{{ currentPermission.orderNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ formatPaymentMethod(currentPermission.paymentMethod) }}</el-descriptions-item>
        <el-descriptions-item label="支付金额">¥{{ currentPermission.price }}</el-descriptions-item>
        <el-descriptions-item label="购买时间">{{ parseTime(currentPermission.purchaseTime) }}</el-descriptions-item>
        <el-descriptions-item label="过期时间">{{ parseTime(currentPermission.expireTime) }}</el-descriptions-item>
        <el-descriptions-item label="权限天数">{{ currentPermission.durationDays }}天</el-descriptions-item>
        <el-descriptions-item label="剩余时间">{{ calcRemainTime(currentPermission.expireTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentPermission.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPermission, getPermission, delPermission, addPermission, extendPermission, batchExtend, refreshStatus } from "@/api/video/permission";

export default {
  name: "Permission",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 权限表格数据
      permissionList: [],
      // 统计数据
      stats: {
        total: 0,
        active: 0,
        expiring: 0,
        expired: 0
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 延长权限对话框
      extendOpen: false,
      // 批量延期对话框
      batchExtendOpen: false,
      // 详情对话框
      detailOpen: false,
      // 当前权限
      currentPermission: null,
      // 延长天数
      extendDays: 7,
      batchExtendDays: 7,
      // 当前到期时间
      currentExpireTime: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userOpenid: null,
        userName: null,
        videoTitle: null,
        orderNo: null,
        paymentMethod: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userOpenid: [
          { required: true, message: "用户OpenID不能为空", trigger: "blur" }
        ],
        videoId: [
          { required: true, message: "视频ID不能为空", trigger: "blur" }
        ],
        durationDays: [
          { required: true, message: "权限时长不能为空", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    newExpireTime() {
      if (!this.currentExpireTime || !this.extendDays) return '';
      const date = new Date(this.currentExpireTime);
      date.setDate(date.getDate() + this.extendDays);
      return this.parseTime(date);
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询权限列表 */
    getList() {
      this.loading = true;
      listPermission(this.queryParams).then(response => {
        this.permissionList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.updateStats();
      });
    },
    /** 更新统计数据 */
    updateStats() {
      this.stats.total = this.permissionList.length;
      this.stats.active = this.permissionList.filter(p => p.status === 'active').length;
      this.stats.expiring = this.permissionList.filter(p => p.status === 'expiring').length;
      this.stats.expired = this.permissionList.filter(p => p.status === 'expired').length;
    },
    /** 计算剩余时间 */
    calcRemainTime(expireTime) {
      if (!expireTime) return '-';
      const now = new Date();
      const expire = new Date(expireTime);
      const diff = expire - now;
      
      if (diff < 0) {
        const hours = Math.floor(-diff / (1000 * 60 * 60));
        return `已过期 ${hours}小时`;
      }
      
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      
      if (days > 0) {
        return `${days}天${hours}小时`;
      }
      return `${hours}小时`;
    },
    /** 获取剩余时间样式 */
    getRemainTimeStyle(row) {
      if (row.status === 'expired') {
        return 'color: #F56C6C; font-weight: bold;';
      } else if (row.status === 'expiring') {
        return 'color: #E6A23C; font-weight: bold;';
      }
      return 'color: #67C23A; font-weight: bold;';
    },
    /** 格式化支付方式 */
    formatPaymentMethod(method) {
      const map = {
        'wechat': '微信小程序',
        'h5': 'H5微信支付',
        'manual': '手动授予'
      };
      return map[method] || method;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        permissionId: null,
        userOpenid: null,
        userName: null,
        videoId: null,
        videoTitle: null,
        durationDays: 7,
        paymentMethod: 'manual',
        price: 0.00,
        purchaseTime: this.parseTime(new Date()),
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.permissionId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "授予播放权限";
    },
    /** 查看详情 */
    handleView(row) {
      this.currentPermission = row;
      this.detailOpen = true;
    },
    /** 延长权限 */
    handleExtend(row) {
      this.currentPermission = row;
      this.currentExpireTime = this.parseTime(row.expireTime);
      this.extendDays = 7;
      this.extendOpen = true;
    },
    /** 提交延长 */
    submitExtend() {
      extendPermission(this.currentPermission.permissionId, this.extendDays).then(response => {
        this.$modal.msgSuccess("延长成功");
        this.extendOpen = false;
        this.getList();
      });
    },
    /** 批量延期 */
    handleBatchExtend() {
      this.batchExtendDays = 7;
      this.batchExtendOpen = true;
    },
    /** 提交批量延期 */
    submitBatchExtend() {
      batchExtend(this.ids, this.batchExtendDays).then(response => {
        this.$modal.msgSuccess("批量延期成功");
        this.batchExtendOpen = false;
        this.getList();
      });
    },
    /** 刷新状态 */
    handleRefreshStatus() {
      this.$modal.confirm('是否确认刷新所有权限的过期状态？').then(function() {
        return refreshStatus();
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("刷新成功");
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addPermission(this.form).then(response => {
            this.$modal.msgSuccess("授予权限成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const permissionIds = row.permissionId || this.ids;
      this.$modal.confirm('是否确认删除权限编号为"' + permissionIds + '"的数据项？').then(function() {
        return delPermission(permissionIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
</style>

